<template>
    <div style="width: 95%;margin: auto;">
  <!-- 这里是条件查询的form -->
      <!-- 
      :inline :把el-form-item 设置 行内元素
       -->
      <el-form :inline="true" :model="building" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="building.number" placeholder="输入楼号" clearable />
        </el-form-item>
        <el-form-item>
          <el-input v-model="building.unit" placeholder="输入单元号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getByConditions(1)">查询</el-button>
        </el-form-item>
      </el-form>
  </div>

  <!-- 添加和批量删除 -->
  <div>
    <el-button type="primary" @click="addBuildingBtn">添加新的楼栋</el-button>
    <el-button type="danger" @click="deleteBatch">删除选中的building</el-button>
  </div>
 <!-- 添加和修改building的弹窗 -->
  <div>
      <!-- 新增用户和修改对话框 -->
      <el-dialog v-model="dialog.visible" :title="dialog.title" width="50%" draggable 
       :before-close="handleClose">
        <!-- 新增用户表单 -->
        <el-form :inline="true" :model="dialog.building" class="demo-form-inline">
            <el-form-item >
                <el-input v-model="dialog.building.number" placeholder="请输入楼号" clearable  style="width: 200px;height: 35px;"/>
            </el-form-item>
              <el-form-item >
                <el-input v-model="dialog.building.unit" placeholder="请输入单元号" clearable  style="width: 200px;height: 35px;"/>
            </el-form-item>
             <!-- <el-select v-model="dialogForUser.user.type"  placeholder="选择用户类型" clearable style="width: 200px;" > -->
             <!-- label：表示显示文本内容  value:表示提交值 -->
            <!-- <el-option label="管理员" :value="1" />
            <el-option label="业主用户" :value="2" />
          </el-select> -->
            <el-input v-model="dialog.building.remarks" :rows="2" type="textarea" placeholder="输入备注信息" style="width: 300px;"/>
            <el-form-item style="margin-top: 20px;">
              <el-button type="primary" @click="addOrEditBuilding">{{dialog.btnText}}</el-button>
              <el-button type="primary" @click="resetAddingDialog">重置</el-button>
            </el-form-item>
          </el-form>
      </el-dialog>
</div>

  <!-- building table -->
  <el-table :data="buildings" 
  style="width: 100%"
  row-key="id"
  @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="id" width="150" />
    <el-table-column prop="number" label="building number" width="200" />
    <el-table-column prop="unit" label="unit" width="120" />
    <el-table-column prop="remarks" label="remarks" width="120" />
    <!-- <el-table-column prop="address" label="Address" width="600" />
    <el-table-column prop="zip" label="Zip" width="120" /> -->
    <el-table-column fixed="right" label="Operations" min-width="120">
      <template #default = "scope">
        <el-button link type="primary" size="small" @click="editBuildingBtn(scope.row)">
          编辑
        </el-button>
        <el-button link type="primary" size="small" @click="delteOne(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页插件 -->
    <div style="width: 95%;margin: 10px auto;">
        <el-pagination background layout="prev, pager, next" 
        v-model:page-size="page.pageSize"
        v-model:current-page="page.currentPage"
        :total="page.total" 
        @current-change="changePage"/>
    </div>
</template>

<script lang="ts" setup>
import { ref,onMounted } from 'vue'
import { buildingApi } from '@/api/building-api'
import { rowKey } from 'element-plus/es/components/table-v2/src/common.mjs';
import { ElMessageBox, ElMessage } from 'element-plus'
//需要一个对象用来放building相关信息
interface Building {
    id:number,
    number:string,
    unit:string,
    remarks:string
}
//一个响应式对象用于展示数据
let building = ref<Building>({
    id:0,
    number:'',
    unit:'',
    remarks:''
})
//做一个空白对象
let blankBuilding = ref<Building>({
    id:0,
    number:'',
    unit:'',
    remarks:''
})

let buildings = ref<Building[]>([]);
let buildingForm = building.value;
//做一个dialog用于修改和添加
let dialog = ref<{visible:boolean, building:Building, title:string, btnText:string}>({
    visible:false,
    building:{
        id:0,
        number:'',
        unit:'',
        remarks:''
    },
    title:'',
    btnText:''
})
//页码类型+响应式对象
interface Page{
  currentPage:number,
  pageSize:number,
  total:number,

}
const page = ref<Page>({
  currentPage:1,
  pageSize:3,
  total:0
})
const handleClick = () => {
  console.log('click')
}

let idsToDelete:number[] = [];
//选中对象后要有一个数组装对应选中buliding
const handleSelectionChange = (checkedBuildings:Building[]) => {
    console.log(checkedBuildings);
    idsToDelete = [];
    for (let index = 0; index < checkedBuildings.length; index++) {
        const building = checkedBuildings[index];
        idsToDelete.push(building.id);
    }
    console.log(idsToDelete);
}


//条件查询
const getByConditions = async (currentPage:number) =>{
    //要把这个building 固定下来不然修改查询表单但是没查询也会影响
    //{...变量}这是浅拷贝 会将buildingForm 和building.value完全用作两个对象
    buildingForm = {...building.value};
    console.log("clciked");
    //let buildingTest = buildings.value[0]
    //每次查询都放回第一页
    //console.log(building.value);
    page.value.currentPage=currentPage;
    let res = await buildingApi.getBuildingsByConditions(page.value.currentPage.toString(),page.value.pageSize.toString(),buildingForm);
    if(res.data.success) {
        console.log("查询成功");
        buildings.value = res.data.data.records;
        page.value.total = res.data.data.total;
        page.value.pageSize = res.data.data.pageSize;
        page.value.currentPage = res.data.data.currentPage;
    }
    console.log(res);
    
}
//翻页操作
const changePage = async() =>{
    
  let res = await buildingApi.getBuildingsByConditions(page.value.currentPage.toString(),page.value.pageSize.toString(),buildingForm);
  if(res.data.success) {
    console.log("查询成功");
    buildings.value = res.data.data.records;
    page.value.total = res.data.data.total;
    page.value.pageSize = res.data.data.pageSize;
    page.value.currentPage = res.data.data.currentPage;
  }
}
//添加按钮设定对应的dialog
const addBuildingBtn = () =>{
    dialog.value.visible=true;
    dialog.value.btnText='add';
    dialog.value.title='添加新building'
}
const editBuildingBtn = (building:Building) =>{
    dialog.value.visible=true;
    dialog.value.btnText='edit';
    dialog.value.title='修改building';
    console.log(building);
    dialog.value.building = {...building};
}
//添加building
const addOrEditBuilding = async () =>{
    console.log(dialog.value.building);
    let res;
    if (dialog.value.btnText == 'add') {
        res = await buildingApi.addBuilding(dialog.value.building);
        if(res.data.success) {
            getByConditions(1);
            dialog.value.visible=false;
            resetAddingDialog();
        }
    } else if(dialog.value.btnText == 'edit') {
        //进行修改
        res = await buildingApi.modifyBuilding(dialog.value.building);
        if(res.data.success) {
            getByConditions(page.value.currentPage);
            resetAddingDialog();
            dialog.value.visible=false;
        }
    }
}
//重置添加building的弹窗
const resetAddingDialog = () =>{
    dialog.value.building = {...blankBuilding.value};
    
}
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('你确定关闭窗口吗,会失去所有内容')
    .then(() => {
        resetAddingDialog();
      done()
    })
    .catch(() => {
      // catch error
    })
}

//批量删除
const deleteBatch = async () =>{
    console.log(idsToDelete.toString());
    let res = await buildingApi.deleteBuilding(idsToDelete.toString())
    if (res.data.success) {
        getByConditions(1);
        //更新ids 数组
        idsToDelete = [];
    }
    
}

//单个删除
const delteOne = async (building:Building) =>{
    let res = await buildingApi.deleteBuilding(building.id.toString())
    if (res.data.success) {
        getByConditions(1);
    }
    
}
//根据条件查询
//一挂载就拿数据
onMounted(()=>{
    getByConditions(1);
})

</script>